<template>
    <action-bar :actionBarData="actionBarData" @addMsg="addMsg" @search="searchInfo" @clearInput="clearSearch"></action-bar>
    <div class="author-list">
        <el-table ref="tableRef" :data="authorList" style="width: 100%" max-height="250" :resizable="true" :show-overflow-tooltip="true">
            <el-table-column v-if="isDeleteBatch" class="selection" fixed type="selection"/>
            <el-table-column class="index" fixed type="index" label="编号" />
            <el-table-column prop="d_name" sortable label="朝代" width="100" />
            <el-table-column prop="a_name" sortable label="姓名" width="120" />
            <el-table-column prop="a_time" sortable label="生辰" width="120" />
            <el-table-column prop="a_synopsis" label="生平简介" />
            <!-- 目前没有足够数量的图片， 暂时不展示这列 -->
            <!-- <el-table-column prop="a_avator" label="图片" width="230">
                <template #default="scope">
                    <div class="img-preview" style="display: flex; align-items: center" v-if="scope.row.avator">
                        <viewer>
                            <img :src="scope.row.avator">
                        </viewer>
                    </div>
                    <div style="display: flex; align-items: center" v-else>
                        暂无图片
                    </div>
                </template>
            </el-table-column> -->
            <el-table-column label="操作" width="170" class-name="handle-cell">
                <template #default="scope">
                    <div class="b-l_handle">
                        <button class="table-fix-btn t-change-btn" @click.prevent="updataRow(scope.row)">
                            <div></div>
                            更改
                        </button>
                        <button class="table-fix-btn t-delete-btn" @click.prevent="deleteRow(scope.$index, scope.row)">
                            <div></div>
                            删除
                        </button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-footer">
            <div class="f-b-r" style="width: 100%;">
                <div>
                    <el-checkbox v-model="isDeleteBatch" label="批量删除" style="margin-right: 1rem;" @change="isShowDeleteSelection"/>
                    <el-button type="danger" class="delete-btn" @click.prevent="getDeleteData">批量删除</el-button>
                </div>
                <div class="demo-pagination-block">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :pager-count="13"
                        :page-sizes="[50, 100, 200, 300, 400, 500, 1000]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="totalLength"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>
    </div>
    <dialog-alert v-if="isdeleteAlert" :data="deleteAlertData" @on-confirm="onConfirm" @on-close="onConcel">
        <div>
            <h2>是否删除下列选中的轮播图？</h2>
            <el-table :data="deleteDate" style="width: 100%" max-height="250" class="delete-table">
                <el-table-column class="index" fixed type="index" label="编号" />
                <el-table-column prop="d_name" sortable label="朝代"/>
                <el-table-column prop="a_name" sortable label="姓名"/>
            </el-table>
        </div>
    </dialog-alert>
    <edit-author-alert v-if="isShowEditAuthorAlert" :type="type" :searchType="searchType" :searchInput="searchInput" ref="editAuthorAlertRef" @onCloseEditAuthorAlert="onCloseEditAuthorAlert" @getAuthorList="getAuthor" @searchInfo="searchInfo"></edit-author-alert>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import manageAuthorStore from '../manage-author.store'
import { IAuthorListModel, IPaginationType } from '../manage-author.model'
import { ElMessage } from 'element-plus'
import EditAuthorAlert from './alert/edit-author-alert.vue'
import { nextTick } from 'process'

const manageAuthorSe = manageAuthorStore()

// 头部工具栏数据
const actionBarData = {
    addButtonMsg: '添加作者信息',
    inputPlaceholder2: '按朝代搜索',
    inputPlaceholder3: '按姓名搜索'
}
let isSearch = ref<boolean>(false) // 用于标记当前表格展示的数据是否来自于搜索
// 清空搜索框
const clearSearch = () => {
    isSearch.value = false
    isFirstSearch.value = false
    currentPage.value = IPaginationType.minCurrentpage
    pageSize.value = IPaginationType.minPageSize
    searchType.value = ''
    searchInput.value = ''
    getAuthor()
}
// 搜索
let isFirstSearch = ref<boolean>(false) // 标记是否点击了搜索框里的查询按钮，如果点击就置为true，清空currentPage和pageNum
let searchInput = ref<string>('') // 用于存储从搜索框传来的数据
let searchType = ref<string>('') // 用于存储从搜索框传来的数据
const searchInfo = (type: string, value: string) => {
    if(!isFirstSearch.value) {
        isFirstSearch.value = true
        currentPage.value = IPaginationType.minCurrentpage
        pageSize.value = IPaginationType.minPageSize
    } 
    const data = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        searchType: type == '2' ? 'D' : 'N',
        searchText: value ? value : ''
    }
    searchType.value = type
    searchInput.value = data.searchText
    manageAuthorSe.getSearchAuthorByDynastyOrName(data).then((res: any) => {
        if(res.status == 'success') {
            isSearch.value = true
            authorList.value = res.results.results2
            totalLength.value = res.results.total
        } else {
            ElMessage.error('搜索失败！')
        }
    })
}

// 弹窗操作
let type = ref<string>('')
let isShowEditAuthorAlert = ref<boolean>(false)
let editAuthorAlertRef = ref<any>(null)
// 添加作者信息
const addMsg = () => {
    type.value = 'add'
    isShowEditAuthorAlert.value = true
}
// 更改作者信息
const updataRow = (value: any) => {
    type.value = 'change'
    isShowEditAuthorAlert.value = true
    nextTick(() => {
        editAuthorAlertRef.value.assignValueToInput(value)
    })
}
// 弹窗内点击取消时
const onCloseEditAuthorAlert = () => {
    isShowEditAuthorAlert.value = false
}

// 获取诗歌信息
const tableRef = ref<any>(null)
let totalLength = ref<number>(0)
let authorList = ref<IAuthorListModel[]>([])
const getAuthor = () => {
    if(isFirstSearch.value) {
        isFirstSearch.value = false
        currentPage.value = IPaginationType.minCurrentpage
        pageSize.value = IPaginationType.minPageSize
    }
    const data = {
        pageNum: currentPage.value,
        pageSize: pageSize.value
    }
    manageAuthorSe.getAuthor(data).then((res: any) => {
        if(res.status = 'success') {
            authorList.value = res.results.results2
            totalLength.value = res.results.total
        }
    })
}

// 分页逻辑
const currentPage = ref(IPaginationType.minCurrentpage) // 当前页码
const pageSize = ref(IPaginationType.minPageSize) // 每月数据条数
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val: number) => {
    pageSize.value = val
    if(isSearch.value) {
        searchInfo(searchType.value, searchInput.value)
    } else {
        getAuthor()
    }
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    if(isSearch.value) {
        searchInfo(searchType.value, searchInput.value)
    } else {
        getAuthor()
    }
    tableRef.value.setScrollTop(0)
}

// 删除
// 批量删除
let isDeleteBatch = ref<boolean>(false)
const deleteBatch = () => {
    isDeleteBatch.value = !isDeleteBatch
}
let deleteDate = ref<any>([])
let isdeleteAlert = ref<boolean>(false)
let deleteIndex = ref<number>(-1) // 当前删除的轮播图的索引
const deleteRow = (index: number, value: any) => {
    isdeleteAlert.value = true
    deleteIndex.value = index
    deleteDate.value = [value]
}
// 获取选中需要删除的数据
const getDeleteData = () => {
    deleteDate.value = tableRef.value.getSelectionRows()
    if(deleteDate.value.length < 1) {
        ElMessage({
            showClose: true,
            message: '请先选择需要删除的数据！',
            type: 'warning',
        })
        return
    }
    isdeleteAlert.value = true
}
// 点击批量输出的checkbox
const isShowDeleteSelection = () => {
    if(!isdeleteAlert.value) tableRef.value.clearSelection()
}

// 询问用户是否删除弹窗
// 弹窗数据
const deleteAlertData = computed(() => {
    return {
        title: '删除作者信息',
        message: '',
        confirmTitle: '删除',
        isShowCancleBtn: true,
        cancleTitle: '取消',
        isShowClose: true
    }
})
// 取消删除
const onConcel = () => {
    isdeleteAlert.value = false
} 
// 确认删除
const onConfirm = () => {
    let aidString = ''
    deleteDate.value.forEach((item: any, index: any) => {
        if(index == (deleteDate.value.length - 1)) {
            aidString += `'${ item.author_id }'`
        } else {
            aidString += `'${ item.author_id }',`
        }
    })
    const data = {
        author_id: aidString
    }
    manageAuthorSe.getDeleteAuthorById(data).then((res: any) => {
        if(res.status == 'success') {
            authorList.value.splice(deleteIndex.value, 1)
            isdeleteAlert.value = false
            // getAuthor()
            if(isSearch.value) {
                searchInfo(searchType.value, searchInput.value)
            } else {
                getAuthor()
            }
            ElMessage({
                showClose: true,
                message: '删除成功！',
                type: 'success',
            })
        } else {
            ElMessage.error('删除失败！')
        }
    })
} 

onMounted(() => {
    getAuthor()
})
</script>

<style lang="less" scoped>
.author-list {
    width: 100%;
    background-color: var(--pc-bg-white);
    margin-top: 1rem;
    border-radius: 0.5rem;
    padding: 1rem 0;
    padding-top: 0rem !important;
    flex: 1;
    background-color: var(--pc-bg-white);
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    max-height: 72vh;
    // :deep(.cell) {
    //     height: 2.5rem;
    //     -webkit-line-clamp: 2;
    // }
    // .cell .img-preview > div > img {
    //     width: 45px;
    //     height: 45px;
    // }
    // :deep(.el-table_2_column_12) {
    //     padding: 0 !important;
    // }
}
:deep(.el-table.delete-table) {
    .el-table__body-wrapper {
        max-height: 30rem !important;
    }
}
</style>